from flask import  request,Blueprint,request
import requests

# from applications.functions.view_html_text import view_html_text   会生成response.text到html文件里

from applications.functions.response import success_response,error_response
from applications.functions.anime_data import anime_search_data,anime_detail_data,anime_video_data


import config
import logging

from urllib.parse import quote_plus  # 添加必要的导入


app = config.anime_app
siwa = config.anime_siwa
siwa_tag = "动漫相关操作"
group_name = "动漫搜索"

anime = Blueprint('anime',__name__)

@app.route('/api/anime/search', methods=['GET'])
@siwa.doc(tags=[siwa_tag], group=group_name)
def anime_search():
    keyword = request.args.get('keyword', '')
    if not keyword:
        return error_response(400, "参数keyword缺失")
    
    try:
        encoded_keyword = quote_plus(keyword)  # 确保从urllib.parse导入
    except Exception as e:  # 添加编码异常处理
        logging.error(f"URL编码失败: {str(e)}")
        return error_response(500, "关键词编码错误")
    
    base_url = "https://d2883ce011d2398b.xdm01.cc"
    # 注意路径为 /search/-------------.html，参数名为 wd 而非 q
    search_url = f"{base_url}/search/-------------.html?wd={encoded_keyword}&submit="

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
        "Referer": f"{base_url}/"
    }
    
    try:
        response = requests.get(search_url, headers=headers, timeout=10)
        response.raise_for_status()  # 检查HTTP错误

        comics = anime_search_data(response.text)

        return success_response(200, "搜索成功", comics["data"])
        
    except requests.exceptions.RequestException as e:
        error_msg = f"网络请求失败: {str(e)}"
        logging.error(f"{error_msg} URL={search_url}")
        return error_response(502, error_msg)
    except Exception as e:
        logging.exception(f"数据处理异常: {str(e)}")  # 记录完整堆栈
        return error_response(500, "服务器处理错误")


@app.route('/api/anime/detail', methods=['GET'])
@siwa.doc(tags=[siwa_tag], group=group_name)
def anime_detail():
    detail_url = request.args.get('url')
    if not detail_url:
        return error_response(400, "参数detail_url缺失")
    try:
        # 2. 配置请求头(防反爬)
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "Referer": "https://www.haoduoman.com/"
        }
        
        # 3. 获取目标网页内容
        response = requests.get(detail_url, headers=headers, timeout=10)
        # view_html_text(detail_url)
        response.raise_for_status()  # 检查HTTP状态码
        chapters = anime_detail_data(response.text)
        return success_response(200, "搜索成功", chapters["data"][0])
        
    except requests.exceptions.RequestException as e:
        error_msg = f"网络请求失败: {str(e)}"
        logging.error(f"{error_msg} URL={detail_url}")
        return error_response(502, error_msg)
    except Exception as e:
        logging.exception(f"数据处理异常: {str(e)}")  # 记录完整堆栈
        return error_response(500, "服务器处理错误")

@app.route('/api/anime/video', methods=['GET'])
@siwa.doc(tags=[siwa_tag], group=group_name)
def anime_video():
    video_url = request.args.get('url')
    print(video_url)
    if not video_url:
        return error_response(400, "参数video_url缺失")
    try:
        # 2. 配置请求头(防反爬)
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "Referer": "https://www.haoduoman.com/"
        }
        
        # 3. 获取目标网页内容
        response = requests.get(video_url, headers=headers, timeout=10)

        response.raise_for_status()  # 检查HTTP状态码

        videos = anime_video_data(response.text)
        # view_html_text(video_url)
        # return success_response(200, "搜索成功", videos)
        return videos
        
    except requests.exceptions.RequestException as e:   
        error_msg = f"网络请求失败: {str(e)}"
        logging.error(f"{error_msg} URL={video_url}")
        return error_response(502, error_msg)
    except Exception as e:
        logging.exception(f"数据处理异常: {str(e)}")  # 记录完整堆栈
        return error_response(500, "服务器处理错误")